package org.tio.sitexxx.service.service.conf;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.sitexxx.service.model.conf.Avatar;

import cn.hutool.core.util.RandomUtil;

/**
 * 头像库
 * @author tanyaowu
 *
 */
public class AvatarService {

	private static Logger log = LoggerFactory.getLogger(AvatarService.class);

	public static final AvatarService me = new AvatarService();

	final static Avatar dao = new Avatar().dao();

	/**
	 * key: id,
	 * value: Avatar
	 */
	private static Map<Integer, Avatar> cacheMap = null;

	private static List<Avatar> cacheList = null;

	/**
	 * 
	 */
	public static void clearCache() {
		synchronized (AvatarService.class) {
			cacheMap = null;
			cacheList = null;
		}
	}

	public boolean save(Avatar avatar) {
		return avatar.save();
	}

	public static void loadData() {
		clearCache();

		Map<Integer, Avatar> tempCache = new HashMap<>();
		List<Avatar> list = null;
		try {
			list = dao.find("select * from avatar");
			if (list == null) {
				list = new ArrayList<>();
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		if (list == null || list.size() == 0) {
			return;
		}

		for (Avatar avatar : list) {
			tempCache.put(avatar.getId(), avatar);
		}
		cacheList = list;
		cacheMap = tempCache;
	}

	public static String nextAvatar() {
		try {
			int index = RandomUtil.randomInt(0, cacheList.size());
			return cacheList.get(index).getPath();
		} catch (Exception e) {
			log.error(e.toString(), e);
			return org.tio.sitexxx.service.model.main.User.DEFAULT_AVATAR;
		}
	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	public static Avatar get(Integer id) {
		if (cacheMap == null) {
			synchronized (AvatarService.class) {
				if (cacheMap == null) {
					loadData();
				}
			}
		}
		Avatar value = cacheMap.get(id);
		return value;
	}

}
